package com.demo2do.jit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.demo2do.jit.entity.Card;
import com.demo2do.jit.entity.OilNumberType;
import com.demo2do.jit.remote.ApiSubscriber;
import com.demo2do.jit.remote.Result;
import com.demo2do.jit.remote.api.JitApi;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnTextChanged;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

import static com.demo2do.jit.R.id.sum;

public class GasActivity extends BaseActivity {

    private static final String TAG = GasActivity.class.getSimpleName();

    @Inject
    JitApi jitApi;

    @Inject
    JitApplication jitApplication;

    @BindView(R.id.scan_gas)
    EditText scanGasEditText;

    @BindView(R.id.vehicle_plate)
    TextView vehiclePlateTextView;

    @BindView(R.id.balance_gas)
    TextView balanceGasTextView;

    @BindView(sum)
    EditText sumEditText;

    @BindView(R.id.buttons_gridview)
    GridView buttonsGridView;

    @BindView((R.id.confirm))
    Button confirmButton;

    @BindView(R.id.full_name)
    TextView fullNameTextView;

    /** 按钮组显示数值 */
    private List<String> numbers = new ArrayList<String>();

    /** 加油卡 */
    private Card card;

    /** cookie */
    private String cookie;

    /** 请先登录错误 */
    private static final String QXDL = "请先登录";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        getActivityComponent().inject(this);
        super.onCreate(savedInstanceState);
        setTheme(R.style.NoTitleTheme);
        setContentView(R.layout.activity_gas);
        ButterKnife.bind(this);

        // initialize gridView
        for (OilNumberType oilNumberType : OilNumberType.values()) {
            numbers.add(oilNumberType.getDescription());
        }
        GasGridViewAdapter adapter = new GasGridViewAdapter(this, numbers);
        buttonsGridView.setAdapter(adapter);

        // get cookie
        cookie = jitApplication.getCookie();

        // set fullName
        String fullName = getIntent().getStringExtra("fullName");
        fullNameTextView.setText(fullName);

    }

    /**
     * event when click search button
     */
    @OnClick(R.id.search)
    void search() {

        String driverCard = scanGasEditText.getText().toString();

        if(TextUtils.isEmpty(driverCard)) {
            toastShort("加油卡号码不能为空");
            return;
        }

        jitApi.search(driverCard, cookie)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showLoading("查询中");
                    }
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        hideLoading();
                    }
                })
                .subscribe(new ApiSubscriber<Result>(GasActivity.this) {
                    @Override
                    protected void httpSuccess(Result result) {
                        if (result.isValid()) {

                            Log.i(TAG, "##search()" + result.getObj());

                            // transform json to card
                            JSONObject jsonObject = result.getObj();
                            card = jsonObject.toJavaObject(Card.class);

                            // update card info
                            vehiclePlateTextView.setText(card.getVehicleName());
                            // update balance gas
                            String amount = card.getCardAmount().toString();
                            balanceGasTextView.setText(card.getCardAmount().toString());

                        } else {

                            // set some editText to ""
                            vehiclePlateTextView.setText("        ");
                            balanceGasTextView.setText("     ");

                            // toast message
                            String message = result.getMsg();
                            toastShort(message);

                            // if message is 请先登录
                            if (QXDL.equals(message)) {
                                finish();
                            }

                        }
                    }
                });

    }

    /**
     * event handler when click oil button
     */
    @OnItemClick(R.id.buttons_gridview)
    void calculate(int position, View view) {

        // get sumEditText value
        String sumText = sumEditText.getText().toString();
        sumText = "".equals(sumText) ? "0.00" : sumText;
        BigDecimal sum = new BigDecimal(sumText);

        // calculate sum
        for(OilNumberType number : OilNumberType.values()) {
            if(position == number.getOrdinal()) {
                sum = sum.add(new BigDecimal(number.getCode()));
            }
        }

        // set sum to sumEditText
        sumEditText.setText(sum.toString());

    }


    /**
     * event when click add oil
     */
    @OnClick(R.id.confirm)
    void addOil() {

        String oilSum = sumEditText.getText().toString();
        if(TextUtils.isEmpty(oilSum)) {
            oilSum = "0.00";
        }
        final BigDecimal oilSumDecimal = new BigDecimal(oilSum);

        if(card == null) {
            toastShort("请先进行油卡查询");
            return;
        }

        if(card.getCardAmount().compareTo(new BigDecimal("0.00")) == -1) {
            toastShort("很抱歉, 油卡余额不够");
            return;
        }

        if(TextUtils.isEmpty(oilSum)) {
            toastShort("加油升数不能为空");
            return;
        }

        if(new BigDecimal("0.00").equals(oilSumDecimal)) {
            toastShort("请输入有效加油量");
            return;
        }

        if (oilSumDecimal.compareTo(card.getCardAmount()) == 1) {
            sumEditText.setText(card.getCardAmount().toString());
            toastShort("本次加油量不能大于" + card.getCardAmount() + "升");
            return;
        }

        if(oilSumDecimal.compareTo(new BigDecimal(100000.00)) == 1 ) {
            sumEditText.setText("100000.00");
            toastShort("单次加油不能超过100000.00升");
            return;
        }

        // create text view for charge message
        TextView message = new TextView(this);
        message.setText("加油卡号：" + card.getDriverCard() + "\n\n" + "全部油升：" + oilSum);
        message.setPadding(0, 15, 0, 10);
        message.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        message.setTextSize(20f);
        message.setTextColor(Color.rgb(255, 102, 51));

        // confirm charge dialog
        new AlertDialog.Builder(this)
                .setView(message)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        charge(oilSumDecimal);
                    }
                })
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        cleanComponent();
                    }
                })
                .show();

    }

    /**
     * charge request
     *
     * @param oilSumDecimal
     */
    protected void charge(BigDecimal oilSumDecimal) {

        jitApi.charge(card.getDriverCard(), oilSumDecimal, cookie)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showLoading("确认加油中");
                    }
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        hideLoading();
                    }
                })
                .subscribe(new ApiSubscriber<Result>(this) {
                    @Override
                    protected void httpSuccess(Result result) {
                        if (result.isValid()) {

                            toastShort("加油成功！");
                            cleanComponent();

                        } else {

                            sumEditText.setText("");

                            // toast message
                            String message = result.getMsg();
                            toastShort(message);

                            // if message is 请先登录
                            if (QXDL.equals(message)) {
                                finish();
                            }

                        }
                    }
                });

    }

    /**
     * clean component's value
     */
    protected void cleanComponent() {
        // set text field to null
        scanGasEditText.setText("");
        vehiclePlateTextView.setText("        ");
        balanceGasTextView.setText("     ");
        sumEditText.setText("");

        // set card to null
        card = null;
    }

    /**
     * event when click logout button
     */
    @OnClick(R.id.logout)
    void logout() {

        jitApi.logout()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showLoading("登出中");
                    }
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        hideLoading();
                    }
                })
                .subscribe(new ApiSubscriber<Result>(this) {
                    @Override
                    protected void httpSuccess(Result result) {
                        if (result.isValid()) {

                            // 清空cookie
                            jitApplication.setCookie(null);

                            // logout method
                            logoutApplication();

                        } else {
                            toastShort(result.getMsg());
                        }
                    }
                });

    }

    /**
     * logout application
     */
    protected void logoutApplication() {
        Intent intent = new Intent(GasActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * limit two decimal method
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @OnTextChanged(value = R.id.sum, callback = OnTextChanged.Callback.TEXT_CHANGED)
    public void onSumTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        sumEditText.setText(s);
                        sumEditText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    sumEditText.setText(s);
                    sumEditText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        sumEditText.setText(s.subSequence(0, 1));
                        sumEditText.setSelection(1);
                        return;
                    }
                }
    }


}
